/**
 * 
 */
package com.lanswon.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.lanswon.common.util.ImageUtil;
import com.lanswon.entity.ImageVO;
import com.lanswon.service.AdminService;
import com.lanswon.service.ImageService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author lanswon
 *
 */

@Controller
@RequestMapping("/front/image")
public class ImageController {
	private static final String FILEURL = "/home/qzsmkweb/attachments/file/";
	private static final String IMGURL = "/home/qzsmkweb/attachments/img/";

	@Autowired
	ImageService imageService;

	@RequestMapping("/url.do")
	@ResponseBody
	public void getUrl(HttpServletRequest request, ServletResponse response, String imgName) throws IOException {
		response.setContentType("application/binary;charset=utf-8");
		OutputStream outs = response.getOutputStream();
		outs.write(imageService.getImgByName(imgName));

		outs.flush();
		outs.close();
	}

	@RequestMapping("/message.do")
	@ResponseBody
	public Object getMessage(HttpServletRequest request, ServletResponse response, String imgName) throws IOException {
		// ImageVO imageVO = ImageService.getMessage(30l);
		JSONArray jsonArray = new JSONArray();
		Map map = new HashMap();

		map.put("checkbox", "json");

		map.put("username", "username");
		map.put("sex", "sex");
		map.put("city", "city");
		map.put("sign", "aaa");
		map.put("experience", "experience");
		map.put("classify", "classify");
		map.put("wealth", "wealth");
		map.put("score", "score");

		for (int i = 0; i < 5; i++) {
			map.put("id", i);
			JSONObject json = JSONObject.fromObject(map);
			jsonArray.add(json);
		}

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 0);
		jsonObject.put("message", "");
		jsonObject.put("data", jsonArray);
		return jsonObject;

	}

	@RequestMapping("/manyFileUpload")
	@ResponseBody
	public Object manyFileUpload(HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> viewMap = new HashMap<>();
		try {
			// List<ProjectFile> fileList = new ArrayList<>();
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					// 记录上传过程起始时的时间，用来计算上传时间
					// int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						String fileType = myFileName.substring(myFileName.lastIndexOf(".") + 1, myFileName.length());
						if (("bmp/png/jpg/jpeg/gif/pdf/doc/docx/xls/xlsx/ppt/pptx/wma/mp3/wav/amr/txt")
								.indexOf(fileType) == -1) {
							viewMap.put("msg", "文件类型不对，不能上传");
							viewMap.put("code", 2);
							return viewMap;
						}
						String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "." + fileType;
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (myFileName.trim() != "") {
							if (ImageIO.read(file.getInputStream()) != null) {
								try {
									String path = IMGURL + newFileName;
									// 上传
									String vmPth = "/qzsmkweb/img/" + newFileName;
									file.transferTo(new File(path));
									viewMap.put("path", vmPth);
								} catch (Exception e) {
									e.printStackTrace();
									viewMap.put("msg", "图片上传失败");
									viewMap.put("code", 3);
									return viewMap;
								}
							} else {
								try {
									// String fileUrl =
									// GetOSSSample.UploadToAliyun(myFileName.substring(myFileName.lastIndexOf(".")),
									// file.getInputStream());
									// String fileSize = FileUtil.getFileSize(file.getSize());
									// ProjectFile projectFile = new ProjectFile();
									/*
									 * projectFile.setName(myFileName.substring(0, myFileName.lastIndexOf(".")));
									 * projectFile.setFileSize(fileSize); projectFile.setFileType(fileType);
									 * projectFile.setFileUrl(fileUrl); fileList.add(projectFile);
									 */
									String path = FILEURL + newFileName;
									// 上传
									String vmPth = "/qzsmkweb/file/" + newFileName;
									file.transferTo(new File(path));
									viewMap.put("path", vmPth);
								} catch (Exception e) {
									e.printStackTrace();
									viewMap.put("msg", "文件上传失败");
									viewMap.put("code", 4);
									return viewMap;
								}
							}
						}
					}
				}
			}
			// viewMap.put("imgList", imgList);
			// viewMap.put("fileList", fileList);
			viewMap.put("code", 1);
		} catch (Exception e) {
			e.printStackTrace();
			viewMap.put("msg", "上传失败");
			viewMap.put("code", 2);
		}
		return viewMap;
	}

}
